<template>
  <div class="employees-container">
    <div class="app-container">
      <PageTools>

        <!-- left具名插槽 -->
        <template #left>
          <span>总记录数: {{ total }} 条</span>
        </template>

        <!-- right具名插槽 -->
        <template #right>
          <el-button type="warning" size="small" @click="$router.push('/import')">excel导入</el-button>
          <el-button type="danger" size="small" @click="hexDownload">excel导出</el-button>
          <el-button
            type="primary"
            size="small"
            @click="showDialog=true"
          >新增员工</el-button>
        </template>
      </PageTools>

      <el-card style="margin-top: 10px;">
        <el-table :data="list" border :default-sort="{prop:'timeOfEntry', order:'descending'}">
          <el-table-column label="序号" type="index" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="工号" prop="workNumber" sortable />
          <el-table-column label="聘用形式">
            <!--   <template slot-scope="scope"> -->
            <template #default="{row}">
              {{ getEmployment(row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" prop="timeOfEntry" sortable />
          <!-- <el-table-column label="账户状态" /> -->
          <el-table-column label="操作" width="280">
            <template #default="{row}">
              <el-button type="text" size="small">查看</el-button>
              <el-button type="text" size="small">分配角色</el-button>
              <el-button type="text" size="small" @click="hDel(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            :current-page="page"
            :page-sizes="[2, 5, 10, 20]"
            :page-size="size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-row>
      </el-card>

      <!-- 新增员工弹层 -->
      <el-dialog
        title="新增员工"
        :visible.sync="showDialog"
        @close="hCloseDialog"
      >
        <empDialog
          v-if="showDialog"
          ref="AddEmployee"
          @close="showDialog=false"
          @updateEmpolyee="hUpdateEmpolyee"
        />
      </el-dialog>

    </div>
  </div>
</template>

<script>
// 导入组件
import empDialog from './empDialog.vue'
import PageTools from '@/components/PageTools'
import { getEmployee, delEmployee } from '@/api/employees'
// 引入枚举数据
import EmployeeEnum from '@/constant/employees'
console.log('EmployeeEnum===>', EmployeeEnum)
// 把 数组 转换成 对象
// [{id:1,value:'正式'},{id:2,value:'非正式'}]
//  转换成 --->  {1:'正式',2:'非正式'}
const hireType = EmployeeEnum.hireType.reduce((sum, item) => {
  sum[item.id] = item.value
  return sum
}, {})
console.log('hireType--', hireType)

export default {
  components: {
    PageTools, empDialog
  },
  data() {
    return {
      // 新增弹层显示隐藏
      showDialog: false,
      // 员工列表数据
      list: [],
      // 页码值
      page: 1,
      // 每页多少条
      size: 2,
      // 总条数
      total: 0
    }
  },
  created() {
    this.loadEmployeeList()
  },
  methods: {
    formatData(list) {
      const map = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }
      console.log(list)
      let header = []
      // header = ['id', 'mobile', 'username', .....]
      // data = [
      //     ['65c2', '1380000002', '管理员', ....],
      //     ['65c3', '1380000003', '孙财', ....],
      // ]
      let data = []
      // 开始代码
      // 找到一个元素
      const one = list[0]
      if (one) {
        header = Object.keys(one).map(key => {
          return map[key]
        })
      }

      // data把list中每一个对象转成 对应的value数组
      data = list.map(val => {
        return Object.values(val)
      })
      console.log('header===>', header)
      console.log('data===>', data)
      return { header, data }
    },
    // 导出Excel
    async hexDownload() {
      const res = await getEmployee()
      if (res.code !== 10000) return
      const { header, data } = this.formatData(res.data.rows)
      import('@/vendor/Export2Excel').then(excel => {
        // excel 传递的是导入的模块对象
        console.log('导入的模块对象excel', excel)
        excel.export_json_to_excel({
          header,
          data,
          // 文件名称
          filename: 'excel-list',
          // 宽度是否自适应
          autoWidth: true,
          // 生成的文件类型
          bookType: 'xlsx'
        })
      })
    },
    // 删除员工
    async doDel(id) {
      try {
        const res = await delEmployee(id)
        console.log('delEmployee', res)
        if (res.code !== 10000) return this.$message.error(res.message)
        this.$message.success(res.message)
        // 当前表格只有一条数据, 删除之后请求上一页的数据
        if (this.list.length === 1) {
          this.page--
          if (this.page <= 0) {
            this.page = 1
          }
        }
        this.loadEmployeeList()
        // 保存数据
      } catch (err) {
        console.log('delEmployee', err)
      }
    },
    // 删除确认
    hDel(id) {
      this.$confirm('确定删除该员工吗?').then(() => {
        this.doDel(id)
      }).catch(err => err)
    },
    // 重置表单
    hCloseDialog() {
      // 调用子组件的方法 resetForm()
      this.$refs.AddEmployee.resetForm()
    },
    // 子传父 刷新列表
    hUpdateEmpolyee() {
      // 关闭弹层
      this.showDialog = false
      // 添加 总条数+1
      this.total++
      // 显示最后一页的数据
      this.page = Math.ceil(this.total / this.size)
      // 刷新数据列表
      this.loadEmployeeList()
    },
    // 获取员工数据
    async loadEmployeeList() {
      try {
        const res = await getEmployee(this.page, this.size)
        console.log('员工列表数据-->', res)
        if (res.code === 10000) this.$message.success(res.message)
        this.list = res.data.rows
        this.total = res.data.total
      } catch (error) {
        console.log(error)
      }
    },
    // 聘用形式
    getEmployment(index) {
      return hireType[index] || '未知...'
    },
    // 分页-- 每页页码值
    handleSizeChange(val) {
      this.size = val
      this.loadEmployeeList()
      console.log(`每页 ${val} 条`)
    },
    // 分页-- 当前页多少条
    handleCurrentChange(val) {
      this.page = val
      this.loadEmployeeList()
      console.log(`当前页: ${val}`)
    }
  }
}
</script>
